import { useMutation } from "@tanstack/react-query";
import { useNavigate } from "react-router";
import { create } from "zustand";
import { createJSONStorage, persist } from "zustand/middleware";

import userService, { type SignInReq } from "@/api/services/userService";
import { STORAGE_PREFIX } from "@/utils/storage";

import { PERMISSION_LIST, PERMISSION_LIST_WITH_CHILDREN } from "@/_mock/assets";
import { toast } from "sonner";
import type { adminUserInfo, adminUserToken } from "#/entity";
import { StorageEnum } from "#/enum";
import errors from "@/router/routes/modules/errors";

const { VITE_APP_HOMEPAGE: HOMEPAGE } = import.meta.env;

type UserStore = {
	adminUserInfo: Partial<adminUserInfo>;
	adminUserToken: adminUserToken;
	// 使用 actions 命名空间来存放所有的 action
	actions: {
		setadminUserInfo: (adminUserInfo: adminUserInfo) => void;
		setadminUserToken: (token: adminUserToken) => void;
		clearadminUserInfoAndToken: () => void;
	};
};

const useUserStore = create<UserStore>()(
	persist(
		(set) => ({
			adminUserInfo: {},
			adminUserToken: {},
			actions: {
				setadminUserInfo: (adminUserInfo) => {
					set({ adminUserInfo });
				},
				setadminUserToken: (adminUserToken) => {
					set({ adminUserToken });
				},
				clearadminUserInfoAndToken() {
					set({ adminUserInfo: {}, adminUserToken: {} });
				},
			},
		}),
		{
			name: `${STORAGE_PREFIX}${StorageEnum.UserStore}`, // name of the item in the storage (must be unique)
			storage: createJSONStorage(() => localStorage), // (optional) by default, 'localStorage' is used
			partialize: (state) => ({
				[`${STORAGE_PREFIX}${StorageEnum.adminUserInfo}`]: state.adminUserInfo,
				[`${STORAGE_PREFIX}${StorageEnum.adminUserToken}`]:
					state.adminUserToken,
			}),
		},
	),
);

export const useUserInfo = () => useUserStore((state) => state.adminUserInfo);
export const useUserToken = () => useUserStore((state) => state.adminUserToken);
export const useUserPermission = () =>
	useUserStore((state) => state.adminUserInfo.permissions);
export const useUserActions = () => useUserStore((state) => state.actions);

export const useSignIn = () => {
	const navigatge = useNavigate();
	const { setadminUserToken, setadminUserInfo } = useUserActions();

	const signInMutation = useMutation({
		mutationFn: userService.signin,
	});

	const signIn = async (data: SignInReq) => {
		const res = await signInMutation.mutateAsync(data);
		console.log(res);
		const { user, token } = res;
		setadminUserToken({ token });
		if (user.role_id === 1) {
			user.permissions = PERMISSION_LIST;
		} else {
			user.permissions = PERMISSION_LIST_WITH_CHILDREN;
		}

		setadminUserInfo(user);
		navigatge(HOMEPAGE, { replace: true });
		toast.success("登录成功");
	};

	return signIn;
};

export default useUserStore;
